//跟进计划列表
var $customerPayFromTable = $('#customerPayFrom');
//搜索客户的列表
var $searchCustomerTable = $('#searchCustomerTable');
var abs = new verjs_select();
//防止表头与表格不对齐
$(window).resize(function () {
    $customerPayFromTable.bootstrapTable('resetView');
});
$(window).resize(function () {
    $searchCustomerTable.bootstrapTable('resetView');
});

$(function () {

    //初始化列表
    customerPayFromList();
    //加载客户列表
    //getCustomerSelect();
    //所属公司列表
    loadCompanySelect();
    // 高级搜索
    $('#btn-search').on('click', function () {
        search($customerPayFromTable, queryParams2);
    });

    searchCustomer2();


})


function customerPayFromList() {
    //先销毁表格
    $customerPayFromTable.bootstrapTable('destroy');
    $customerPayFromTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/customerPay/selectCustomerPayList',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerPayId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
            {title: '客户名称',field: 'customerName', align: 'left', valign: 'middle'},
            {title: '客户编号',field: 'customerNumber', align: 'left', valign: 'middle'},
            {title: '充值金额',field: 'payMoney', align: 'left', valign: 'middle'},
            {title: '充值码',field: 'payNumber', align: 'left', valign: 'middle'},
            {title: '充值类型', field: 'payType', align: 'left', valign: 'middle',formatter: payTypeFormat},
            //{title: '充值状态', field: 'payStatus', align: 'left', valign: 'middle',formatter: payStatusFormat},
            {title: '所属人', field: 'haveUserName', align: 'left', valign: 'middle'},
            {title: '所属公司', field: 'haveCompanyName', align: 'left', valign: 'middle'},
            {title: '操作人', field: 'createPeopleName', align: 'left', valign: 'middle'},
            {title: '操作时间', field: 'createTm', sortable: true,align: 'left', valign: 'middle'},
            {title: '操作',field: 'operate',align: 'left',formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#taxDiscFrom').css({
                minWidth: $('#taxDiscFrom').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}


function searchOrderList() {
    $('.all').addClass('active-second');
    $('.today').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $('.year').removeClass('active-second');
    $("#dateType").val("all");
    $customerPayFromTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
}

function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.dataType = 2;//充值类型查询普通充值的
    return params;
}

function queryParams2(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.customerName = $.trim($('#customerName2').val());//客户名称
    params.userName = $.trim($('#userName').val());//所属人
    params.companyId = $.trim($('#companySelect').val());//所属公司
    params.dataType = 2;//充值类型查询普通充值的
    return params;
}

function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 获得客户名称下拉
 */
function getCustomerSelect(){
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/customerController/getCustomerListByComp',
        cache : false,
        data:{
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '<option value="">请选择</option>';
                $.each(data.data, function(n, value) {
                    html += "<option value=" + value.customerId + ">" +  value.customerName + "</option>";
                });

                $('#customerInput').html(html).selectpicker('refresh');
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}


/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" data-toggle="collapse" data-target="#updatePay" aria-expanded="false" aria-controls="updatePay" ' +
        'onclick="updatePay(\''+row.customerId+'\',\''+row.customerPayId+'\',\''+row.payMoney+'\',\''+row.customerName+'\',\''+row.customerNumber+'\')">修改</button>';
    /*html += '<button class="btn btn-default" ' +
        'onclick="delTaxDisc(\''+row.companyId+'\')">删除</button>';*/

    html += '</ul></div>'
    return html;
}

/**
 * 获得客户名称下拉
 */
function getCustomerSelect2(customerId){
    console.info("customerId  "+customerId);
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/customerController/getCustomerListByComp',
        cache : false,
        data:{
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '<option value="">请选择</option>';
                $.each(data.data, function(n, value) {
                    if (value.customerId == customerId){
                        html += "<option value=" + value.customerId + " selected >" +  value.customerName + "</option>";
                    }else {
                        html += "<option value=" + value.customerId + ">" +  value.customerName + "</option>";
                    }

                });

                $('#customerInput2').html(html).selectpicker('refresh');
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

//回显
function updatePay(customerId,customerPayId,payMoney,customerName,customerNumber) {

    $("#customerPayIdHide").val(customerPayId);
    $("#payMoney2").val(payMoney);
    $("#customerInput2").val(customerName);
    $("#customerIdHide").val(customerId);
    $("#customerNumber").val(customerNumber);
    //getCustomerSelect2(customerId);
}

//修改
function subUpdateCustomerPay() {
    $.alert({
        title: '提示',
        content: '您确认要修改客户充值信息吗？',
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    var customerPayId = $("#customerPayIdHide").val();
                    var customerId = $("#customerIdHide").val();
                    var payMoney = $("#payMoney2").val();
                    var jsonData = {
                        "chsCustomerPayId":customerPayId,
                        "customerId":customerId,
                        "payMoney":payMoney,
                        "payType":2
                    }
                    $.ajax({
                        url: '/customerPay/updateCustomerPay',
                        type: 'POST',
                        dataType: "json",
                        contentType: "application/json;charset=utf-8",
                        data: JSON.stringify(jsonData),
                        success: (function (data) {
                            if (data.code == "000000") {
                                $.alert({
                                    title: '提示',
                                    content: '操作成功！',
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'btn-primary',
                                            action: function () {
                                                window.location.reload();
                                            }
                                        }
                                    }
                                });
                            } else {
                                $.alert(data.message);
                            }
                        }),
                        error: (function (res) {
                            $.alert('操作失败，请稍后再试!');
                        })
                    });
                }
            }
        }
    });

}
var statusType;
//添加充值
function addShiftWallet() {
    if (!statusType){
        $.alert("您还没有录入客户转入信息");
        return;
    }
    var customerId = statusType;
    var payMoney = $("#"+statusType+"wallet").val();
    var jsonData = {
        "customerId":customerId,
        "payMoney":payMoney,
        "payType":2
    }
    $.ajax({
        url: '/customerPay/saveCustomerPay',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '操作成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                window.location.reload();
                            }
                        }
                    }
                });
            } else {
                $.alert(data.message);
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
}

function clearAllData() {
    window.location.reload();
}


function getCompanyTaxNumber(companyId) {
    $.ajax({
        url: "/sysCompany/selectCompanyTaxNumber?companyId="+companyId,
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            var data = data.data;
            $("#taxNumber").val(data);
        },
        error: function (err) {
            console.log(err);
        }
    })
}

function payTypeFormat(value, row, index) {
    var html = "";
    if (value == 1){
        html = "普通充值";
    }
    if (value == 2){
        html = "转入额";
    }
    return html;
}

function payStatusFormat(value, row, index) {
    var html = "";
    if (value == 0){
        html = "充值中";
    }
    if (value == 1){
        html = "已到账";
    }
    return html;
}

/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    if (time == 'today') {//今天
        $('.today').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisToday");
    }
    $customerPayFromTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 加载公司下拉列表
 */
function loadCompanySelect() {
    $.getJSON("/sysCompany/selectCompanies", function (data) {
        if (data.code == '000000') {
            var optionHtml = '';
            var optionArr = data.data;
            var optionSelected = $('#companySelect option:selected').val();
            //公司搜索条件下拉框
            var searchCompanyOptionHtml = '<option onclick="changeName('+0+');" value="">全部</option>';
            optionArr.map(function (item, index) {
                searchCompanyOptionHtml += '<option onclick="changeName('+item.companyId+');" value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $('#companySelect').html(searchCompanyOptionHtml);
            var selectDate = [];
            for (var i = 0, len = data.data.length; i < len; i++) {
                var company = data.data[i];
                var selectCompany = {};
                selectCompany.id = company.companyId;
                selectCompany.name = company.companyName;
                selectDate.push(selectCompany);
            }
            /*abs.render({
                elem: "#search",
                data: selectDate,
                init_value: [1],
                body_height: 300,
                checkbox: true,
                name: "test"
            });*/
            $('#searchoption-list').css('z-index',1000);
            $('#companySelect').selectpicker({
                sanitize: true,
                size: 8
            });
        }
    });
}

//搜索客户
function searchCustomer() {
    //先销毁表格
    $searchCustomerTable.bootstrapTable('destroy');
    $searchCustomerTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/customerController/selectCustomerPreciseSearch',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        queryParams: searchCustomerParams,//查询参数
        columns: [
            {title: '主键', field: 'customerId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
            {title: '客户名称',field: 'customerName', align: 'left', valign: 'middle'},
            {title: '客户编码',field: 'customerNumber', align: 'left', valign: 'middle'},
            {title: '操作',field: 'operate',align: 'left',formatter: genderOpt2}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#taxDiscFrom').css({
                minWidth: $('#taxDiscFrom').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function searchCustomer2() {
    //先销毁表格
    $searchCustomerTable.bootstrapTable('destroy');
    $searchCustomerTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        queryParams: searchCustomerParams,//查询参数
        columns: [
            {title: '主键', field: 'customerId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
            {title: '客户名称',field: 'customerName', align: 'left', valign: 'middle'},
            {title: '客户编码',field: 'customerNumber', align: 'left', valign: 'middle'},
            {title: '操作',field: 'operate',align: 'left',formatter: genderOpt2}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#taxDiscFrom').css({
                minWidth: $('#taxDiscFrom').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 自定义操作列内容
 */
function genderOpt2(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" data-toggle="collapse"  id="'+row.customerId+'walletbut" ' +
        'onclick="addWallet(\''+row.customerId+'\')">点击填写转入额度</button>';
    html += '<button class="btn btn-default" data-toggle="collapse"  id="'+row.customerId+'numberbut" ' +
        'onclick="editCustomerNumber(\''+row.customerId+'\')">点击转换客户编码</button>';
    html += '<input id="'+row.customerId+'wallet"  style="width: 150px;" type="hidden" class="form-control"  ' +
        'onkeyup="value=value.replace(/^\\D*(\\d*(?:\\.\\d{0,2})?).*$/g, \'$1\')" placeholder="请输入转入额度">';
    html += '</ul></div>'
    return html;
}

//编辑转入额
function addWallet(inputId) {
    //初始化样式
    if (statusType){
        $("#"+statusType+"wallet").attr('type','hidden');
        $("#"+statusType+"walletbut").show();
        $("#"+statusType+"numberbut").show();
    }
    statusType = (inputId);
    $("#"+inputId+"wallet").attr('type','text');
    $("#"+inputId+"walletbut").hide();
    $("#"+inputId+"numberbut").hide();
}

//修改客户编码
function editCustomerNumber(customerId) {
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/customerController/updateCustomerNumber',
        cache : false,
        data:{
            customerId:customerId
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {
                $.alert('操作成功!');
                $searchCustomerTable.bootstrapTable('refreshOptions', {pageNumber: 1});
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

function searchCustomerParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    var type = $("#searchCustomer").val();
    if (type ==1){
        params.customerName = $("#searchCustomerInput").val();
    }else if(type ==2){
        params.customerNumber = $("#searchCustomerInput").val();
    }
    return params;
}

function resetSearch() {
    $("#customerName2").val("");
    $("#userName").val("");
    $("#companySelect").val("");
}

